package io.renren.modules.noc.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.JsonObject;
import io.renren.common.sms.AliyunSms;
import io.renren.common.sms.YxuntongSms;
import io.renren.common.utils.Constant;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.RandomUtil;
import io.renren.modules.noc.dao.*;
import io.renren.modules.noc.entity.*;
import io.renren.modules.noc.service.NocMemberService;
import io.renren.modules.noc.service.NocMsgService;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.shiro.ShiroUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Service("nocMemberService")
public class NocMemberServiceImpl extends ServiceImpl<NocMemberDao, NocMemberEntity> implements NocMemberService {

    @Autowired
    private NocMemberDao dao;
    @Autowired
    private NocLyDao lyDao;
    @Autowired
    private NocRoleDao roleDao;
    @Autowired
    private NocTemplateDao nocTemplateDao;
    @Autowired
    private NocReadCardDao nocReadCardDao;
    @Autowired
    private NocBusinessDao nocBusinessDao;
    @Autowired
    private NocMsgService nocMsgService;

    //"尊敬的{0},您{1}的VIP电子门票链接 {2} ,请直接现场刷闸机入场";
    private final String _content = "{0}您已成功预登记为{1}参观观众！以下为您的入场门票链接 {2} 7月18-22日青岛国际博览中心(即墨区温泉镇温泉二路7-1号)全新阵容，世界顶级智能制造规模.询4006767200 回T退";
    private final String _contentl = "尊敬的{0},您注册的济南西部会展中心第19届家具博览会的预登记观众电子门票链接为 preg.jinnoc.com/t/{0} 凭码入场免购百元门票！回T退";

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        SysUserEntity userEntity = ShiroUtils.getUserEntity();
        Map<String, Object> params2 = new HashMap<>();
        params2.putAll(params);
        String col1 = (String)params.get("col1");
        String col2 = (String)params.get("col2");
        String col15 = (String)params.get("col15");
        String ly = (String)params.get("ly");
        String templateId = (String) params.get("templateId");
        //权限控制
        if(StringUtils.isEmpty(templateId) && !"admin".equals(userEntity.getUsername())){
            templateId = "-1";
        }
        //获取系统用户的来源权限
        Map<String,Object> roleMap = new HashMap<>();
        roleMap.put("tid",templateId);
        roleMap.put("uid",userEntity.getUserId());
        List<String> in = roleDao.getUserLyRole(roleMap);

        IPage<NocMemberEntity> page = this.page(
                new Query<NocMemberEntity>().getPage(params),
                new QueryWrapper<NocMemberEntity>()
                        .eq(StringUtils.isNotBlank(templateId),"tid", templateId)
                        .eq(col15 != null, "col15", col15)
                        .eq(StringUtils.isNotBlank(ly),"ly", ly)
                        .like(StringUtils.isNotBlank(col2),"col2", col2)  //公司
                        .like(StringUtils.isNotBlank(col1),"col1", col1)  //手机号
                        .in(in.size()>0,"ly",in)  //权限
                        //.or().like(StringUtils.isNotBlank(col1),"col20", col1)  //二维码
                        .apply(params.get(Constant.SQL_FILTER) != null, (String)params.get(Constant.SQL_FILTER))
        );
        setLyRemark(page);
        return new PageUtils(page);
    }

    public void setLyRemark(IPage<NocMemberEntity> page){
        for(NocMemberEntity nocMemberEntity : page.getRecords()){
            String ly = nocMemberEntity.getLy();
            Integer tid = nocMemberEntity.getTid();
            Map<String,Object> p = new HashMap<>();
            p.put("ly",ly);
            p.put("tid",tid);
            List<NocLyEntity> lyList = lyDao.selectByMap(p);
            if(lyList!=null&&lyList.size()>0) {
                nocMemberEntity.setLy(lyList.get(0).getRemark());
            }
        }
    }

    @Override
    public List<Map<String,Object>> memberCount(Map<String,Object> map){
        SysUserEntity userEntity = ShiroUtils.getUserEntity();
        //获取系统用户的来源权限
        Map<String,Object> roleMap = new HashMap<>();
        roleMap.put("tid",map.get("tid"));
        roleMap.put("uid",userEntity.getUserId());
        List<String> in = roleDao.getUserLyRole(roleMap);
        map.put("lys",in);
        return dao.memberCount(map);
    }

    @Override
    public String getNextErCode(String pre){
        return dao.getNextErCode(pre);
    }


    @Override
    public void sendMsg(Integer templateId, NocMemberEntity nocMemberEntity, NocTemplateEntity template, String url){
        //String _content = "尊敬的{0},您{1}的VIP电子门票链接 {2} ,请直接现场刷闸机入场";
        //templateId不能为空
        if(templateId==null){
            return;
        }
        Map<String,Object> map = new HashMap<>();
        map.put("tid",templateId);
        String col1 = nocMemberEntity.getCol1();
        if(StringUtils.isNotEmpty(col1)) {
            map.put("col1", nocMemberEntity.getCol1());
        }
        String col15 = nocMemberEntity.getCol15();
        if(StringUtils.isNotEmpty(col15)) {
            map.put("col15", nocMemberEntity.getCol15());
        }
        List<NocMemberEntity> list = this.dao.selectByMap(map);
        //url = url.replace("http://","");
        //url = url.replace("https://","");
        for(NocMemberEntity member:list){
            //String content = _contentl;
            Map<String,Object> maptest = nocMsgService.qunfa();
            String content = maptest.get("content").toString();
            String label = maptest.get("label").toString();
            String mobile = member.getCol1();
            String name = member.getCol3();
            if(name!=null&&mobile!=null&&template!=null&&StringUtils.isNotEmpty(template.getMsgAccout())) {
                /*content = content.replace("{0}", name);
                content = content.replace("{1}", template.getTemplate());
                content = content.replace("{2}", url + "t/" + member.getId());
                content = label+content;
                YxuntongSms.sendMsg(template.getMsgyxAccount(),template.getMsgyxPwd(),mobile,content);
                System.out.println(mobile + ":" + content);*/
                JSONObject json = new JSONObject();
                json.put("name", name);
                json.put("name1", template.getTemplate());
                json.put("code", member.getId());
                AliyunSms.sendMsg(template.getMsgAccout(), template.getMsgPwd(), mobile, label, content, json.toJSONString());
            }
        }
    }

    @Override
    public void sendErcodeMsg(List<NocMemberEntity> list,String url){
        //String _content = "尊敬的{0},您{1}的VIP电子门票链接 {2} ,请直接现场刷闸机入场";
        //url = url.replace("http://","");
        //url = url.replace("https://","");
        for(NocMemberEntity member:list){
            Map<String,Object> maptest = nocMsgService.qunfa();
            String content = maptest.get("content").toString();
            String label = maptest.get("label").toString();
            String mobile = member.getCol1();
            String name = member.getCol3();
            Integer tid = member.getTid();
            NocTemplateEntity template = nocTemplateDao.selectById(tid);
            if(name!=null&&mobile!=null&&template!=null&&StringUtils.isNotEmpty(template.getMsgAccout())) {
                /*content = content.replace("{0}", name);
                content = content.replace("{1}", template.getTemplate());
                content = content.replace("{2}", url + "t/" + member.getId());
                content = label+content;
                YxuntongSms.sendMsg(template.getMsgyxAccount(),template.getMsgyxPwd(),mobile,content);*/
                JSONObject json = new JSONObject();
                json.put("name", name);
                json.put("name1", template.getTemplate());
                json.put("code", member.getId());
                AliyunSms.sendMsg(template.getMsgAccout(), template.getMsgPwd(), mobile, label, content, json.toJSONString());
                System.out.println(mobile + ":" + json.toJSONString());
            }
        }
    }

    @Override
    public  List<NocMemberEntity> getRepay(Page<Map<String,Object>> page, Map<String, Object> params){
        SysUserEntity userEntity = ShiroUtils.getUserEntity();
        //获取系统用户的来源权限
        if(!"admin".equals(userEntity.getUsername())) {
            params.put("repay", userEntity.getRemark());
        }
        return dao.getRepay(page,params);
    }

    @Override
    public  Map<String,Object> getMemberId(Map<String,Object> map){
        return dao.getMember(map);
    }


    @Override
    public void sendDaMemberMsg(Integer memberId){
        //根据id判断采购商col37字段是否为“1”，若为1，取得该采购商
        NocMemberEntity member = dao.getMemberPhone(memberId);
        if (member != null) {//只处理col37为1的采购商
            String content1 = "【中国制博会】尊敬的采购商您好，感谢参观2019第十八届中国国际装备制造业博览会，9月2日9:30 W4馆采购商大会，请您携带名片参与大会现场抽奖活动，期待您准时出席！如有调整，请及时告知18941656006（同微信）回T退";//采购商进入后，给展商发送的短信内容
            String barCode = member.getCol20();//采购商入场二维码
            Integer tid = member.getTid();//展会id
            List<NocReadCardEntity> rcList = nocReadCardDao.getPCName(barCode);
            if (rcList.size()>1){
                System.out.println("重新进入会场，不发送大客户短信");
            }
            if(rcList.size()==1){
                String content2 = member.getCol1();
                //根据展会id查询展会短信账号密码
                NocTemplateEntity msgAccountAndPwd = nocTemplateDao.getMsgAccountAndPwd(tid);
                String msgyxAccount = msgAccountAndPwd.getMsgyxAccount();
                String msgyxPwd = msgAccountAndPwd.getMsgyxPwd();
                if (StringUtils.isNotEmpty(msgyxAccount) && StringUtils.isNotEmpty(msgyxPwd)) {
                    //给大客户发送短信
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = new Date();
                    try {
                         date = sdf.parse("2019-9-2 12:00:00");
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    if(new Date().getTime()<date.getTime()){
                        System.out.println("成功进入");
                        YxuntongSms.sendMsg(msgyxAccount, msgyxPwd, content2, content1);
                        System.out.println("--------："+content1+"--------------");
                    }


                }
            }

        }

    }
    /**
     * @Author wangfj
     * @Description 给大客户发送短信
     * @Date 9:07 2019/7/16 0017
     * @Param [memberId]
     * @return void
     **/
    @Override
    public void sendMemberMsg(Integer memberId) {
        //根据id判断采购商col37字段是否为“1”，若为1，取得该采购商
        NocMemberEntity member = dao.getMemberPhone(memberId);
        if (member != null) {//只处理col37为1的采购商
            String content1 = "尊敬的展商，采购商大会提醒您，与您配对的采购商已到展会现场，请与接待人员（胡梦：18560650513）联系，并前往洽谈区 回T退";//采购商进入后，给展商发送的短信内容
            String phones = member.getCol38();//展商手机号
            String barCode = member.getCol20();//采购商入场二维码
            Integer tid = member.getTid();//展会id
            List<NocReadCardEntity> rcList = nocReadCardDao.getPCName(barCode);
            if (rcList.size()>1){
                System.out.println("重新进入会场，不发送大客户短信");
            }
            if(rcList.size()==1){
                NocReadCardEntity pm = rcList.get(0);
                String pcName = pm.getPcName();
                if (StringUtils.isEmpty(pcName)) {
                    pcName = "人工扫码口";//门禁名
                }
                String content2 = member.getCol2() + "，" + member.getCol3().substring(0, 1) + "经理:" + member.getCol1() + "，采购商已从" + pcName + "进入展馆 回T退";
                System.out.println(content1);
                //根据展会id查询展会短信账号密码
                NocTemplateEntity msgAccountAndPwd = nocTemplateDao.getMsgAccountAndPwd(tid);
                String msgyxAccount = msgAccountAndPwd.getMsgyxAccount();
                String msgyxPwd = msgAccountAndPwd.getMsgyxPwd();
                if (StringUtils.isNotEmpty(msgyxAccount) && StringUtils.isNotEmpty(msgyxPwd)) {
                    //给工作人员发送短信  17660454126,15621494724
                    YxuntongSms.sendMsg(msgyxAccount, msgyxPwd, "17660454126", content2);
                    YxuntongSms.sendMsg(msgyxAccount, msgyxPwd, "15621494724", content2);
                    System.out.println("--------给工作人员:18560650513,18753294976发送短信："+content2+"--------------");
                    if (StringUtils.isNotEmpty(phones)) {
                        //给展商发送短信
                        String[] phone = phones.split(",");
                        for (int i = 0; i < phone.length; i++) {
                            //YxuntongSms.sendMsg(msgyxAccount, msgyxPwd, phone[i], content1);
                            //System.out.println("--------给展商"+phone[i]+"发送短信："+content1+"--------------");
                        }
                    }
                }
            }

        }

    }
    /**
     * @Author wangfj
     * @Description 根据展商和采购商的标签进行匹配，为双方发送匹配短信
     * @Date 9:08 2019/7/16 0017
     * @Param [memberId]
     * @return void
     **/
    @Override
    public void sendMatchMsg(Integer memberId){
        NocMemberEntity member = dao.getMemberById(memberId);
        if(member != null) {
            Integer tid = member.getTid();
            //根据展会id查询展会短信账号密码
            NocTemplateEntity msgAccountAndPwd = nocTemplateDao.getMsgAccountAndPwd(tid);
            String msgyxAccount = msgAccountAndPwd.getMsgyxAccount();
            String msgyxPwd = msgAccountAndPwd.getMsgyxPwd();
            String barCode = member.getCol20();
            List<NocReadCardEntity> rcList = nocReadCardDao.getPCName(barCode);
            if (rcList.size()>1){
                System.out.println("重新进入会场，不发送匹配短信");
            }
            if(rcList.size()==1) {
                //发送匹配短信
                List<NocBusinessEntity> businessList = nocBusinessDao.getBusinessByMemberLabel(memberId);
                if (businessList.size() != 0) {
                    HashSet<Integer> noRepeatRandom = RandomUtil.getNoRepeatRandom(3, businessList.size());
                    for (Integer i : noRepeatRandom) {
                        NocBusinessEntity business = businessList.get(i);
                        String mobile = business.getMobile();
                        String content3 = "尊敬的展商，采购商大会提醒您，帮您配对的采购商:" + member.getCol2() + "，" + member.getCol3().substring(0, 1) + "经理:" + member.getCol1() + "，已到展会现场，请予以洽谈 回T退";
                        String content4 = "尊敬的买家，采购商大会提醒您，根据您的采购需求已帮您配对卖家:" + business.getCompany() + "，" + business.getName().substring(0, 1) + "经理:" + mobile + "，请予以洽谈 回T退";
                        YxuntongSms.sendMsg(msgyxAccount, msgyxPwd, mobile, content3);
                        System.out.println("--------给展商" + mobile + "发送短信：" + content3 + "--------------");
                        YxuntongSms.sendMsg(msgyxAccount, msgyxPwd, member.getCol1(), content4);
                        System.out.println("--------给采购商" + member.getCol1() + "发送短信：" + content4 + "--------------");
                    }

                }
            }
        }
    }

    @Override
    public void updateSign(Map<String,Object> map){
        dao.updateSign(map);
    }

    @Override
    public Integer selectCount(Map<String,Object> map){
        return dao.selectCount(map);
    }

    @Override
    public List<NocMemberEntity> getErcodeByOpenId(Map<String,Object> map){
        return dao.getErcodeByOpenId(map);
    }

    @Override
    public Integer getMemberId(String barCode){
        Integer memberId = 100000;
        Map<String,Integer> memberIdMap = dao.getMemberId(barCode);
        if(memberIdMap!=null){
             memberId = memberIdMap.get("id");
        }
        return memberId;
    }

    @Override
    public Map<String,Object> getMemberByErCode(String ercode){
        return dao.getMemberByErCode(ercode);
    }


    @Override
    public Map<String,Integer> getMemberTid(String barCode){
        return dao.getMemberTid(barCode);
    }

}
